//
//  WBOAuthWebController.swift
//  微博
//
//  Created by hejinyin on 2017/9/8.
//  Copyright © 2017年 WangQiang. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthWebController: UIViewController {
    
    fileprivate  lazy var webView :UIWebView = {
        let webView = UIWebView.init()
        webView.scrollView.isScrollEnabled = false
        webView.scalesPageToFit = true
        webView.delegate = self
        return webView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "登录新浪微博"
        
        view.addSubview(webView)
        
        webView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        let urlStr  = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        
        webView.loadRequest(URLRequest.init(url: URL.init(string: urlStr)!))
        let leftItem = UIBarButtonItem.init(title: "返回", target: self, action: #selector(close))
        navigationItem.leftBarButtonItem = leftItem
        
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "自动填充", target: self, action: #selector(autoFill))
        
        navigationController?.navigationBar.tintColor = UIColor.orange
        
    }
    @objc func close(){
        SVProgressHUD.dismiss()
        dismiss(animated: true)
    }
    @objc func autoFill(){
        let js = "document.getElementById('userId').value = 'wang68543@sina.com'; " +
        "document.getElementById('passwd').value = 'asdfghjkl313';"
        
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

//MARK: =========== webView deleagte ===========
extension WBOAuthWebController:UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let url = request.url,
            let query = url.query{
            if url.absoluteString.hasPrefix(WBRedirectURI){
                if query.hasPrefix("code=")  {
                    
                   let code =  query.substring(from: query.index(query.startIndex, offsetBy: "code=".lengthOfBytes(using: String.Encoding.utf8)))
                    
                    WBNetWorkManager.sharedInstance.loadAccessToken(code: code, compeletion: { (isSuccess) in
                        
                    })
                    
                }else{
                    print("取消授权")
                    close()
                }
                return false
            }
        }
      
        return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.showInfo(withStatus: error.localizedDescription)
    }
}
